package com.magic.util;

import java.io.InputStream;

import com.magic.vo.file.FileVo;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiniuUtils {

	static String accessKey = "TrLYuKilB1Q-oTeFKrBq0JeTT2bZ3z_CP3J6xObh";
	
	static String secretKey = "cMuxIeVtI8cZWkG-dj7Fp9TormIQL4ApKUtJXwrX";
	
	static String bucket = "qugou";
	
	static String domain = "qugouimg.shenzjd.com";

	/**
	 * 七牛云上传
	 * 
	 * @param inputStream
	 * @return map key文件名，hash文件hash值， fsize大小， finalUrl下载地址
	 */
	public static FileVo upload(InputStream inputStream) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(inputStream, key, upToken, null, null);
			FileVo fileVo = response.jsonToObject(FileVo.class);
			return fileVo;
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				// ignore
			}
		}
		return null;
	}

	public static String getURL(String key) {
		// 1.构建公开空间访问链接
		try {
			String url = "";
			url = "http://" + domain + "/" + key;
			// 2.进行私有授权签名
			Auth auth = Auth.create(accessKey, accessKey);
			// 自定义链接过期时间(单位s)
			long expireInSeconds = 3600;// 1小时
			// 生成下载链接
			String finalUrl = auth.privateDownloadUrl(url, expireInSeconds);
			return finalUrl;
		} catch (Exception e) {
			return "";
		}
	}
}
